﻿using Common.Communal;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Warehouse.API.APP.Commands;
using System.Net.Http.Json;

namespace Warehouse.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class inventoryTransactionController : ControllerBase
    {
        IMediator mediator;
        IHttpClientFactory httpClientFactory;

        public inventoryTransactionController(IMediator mediator, IHttpClientFactory httpClientFactory)
        {
            this.mediator = mediator;
            this.httpClientFactory = httpClientFactory;
        }
        [HttpPost]
        public async Task<ApiResult<int>> inventoryTransactionAdd(InventoryTransactionAdd add) { 
            var result = await mediator.Send(add);
            
            // 写库成功后，主动通知读侧进行实时推送
            if (result.Code == Common.Communal.EnumCode.Ok)
            {
                try
                {
                    var client = httpClientFactory.CreateClient();
                    // TODO: 修改为实际读侧基址 - 请根据您的实际部署地址修改
                    client.BaseAddress = new Uri("http://localhost:5028");
                    
                    // 构建通知载荷 - 获取所有数据（不按产品名筛选），让前端自动显示
                    var payload = new {
                        pageindex = 1,
                        pagesize = 50, // 增加页面大小，确保能看到更多数据
                        ProductName = "" // 空字符串表示获取所有数据
                    };
                    
                    // 调用读侧的通知接口，触发实时更新
                    var response = await client.PostAsJsonAsync("/api/ReportSummary/NotifyInventoryChanged", payload);
                    response.EnsureSuccessStatusCode();
                    
                    Console.WriteLine($"成功通知读侧进行实时更新，产品名称: {add.ProductName}");
                }
                catch (Exception ex)
                {
                    // 记录通知失败，但不影响主业务流程
                    Console.WriteLine($"通知读侧实时更新失败: {ex.Message}");
                }
            }
            return result;
        }
    }
}
